<template>
  <!-- v-loading="true" -->
  <div>

    <pageSearch :searchFormConfig="searchFormConfig" @searchSubmit="searchSubmit" />
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">
      <template #ckg="{ row }">
        {{ row.chang + 'x' + row.kuan + 'x' + row.gao }}
      </template>
      <template #level="{ row }">
        {{ filterStatusName(row.level) }}
      </template>
      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="50%" top="20vh" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <el-form ref="ruleFormRef" v-loading='!DialoLoading' :model="ruleForm" status-icon :rules="rules"
        label-width="120px" class="demo-ruleForm">

        <el-row :gutter="20">


          <el-col :span="24">
            <el-form-item label="封装描述文件" v-if='DialoLoading' prop="linkList">
              <uploadFiles v-model="ruleForm.linkList" @onPreviewFn="onPreviewFN"></uploadFiles>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="封装文件编号" prop="paccode">
              <el-input v-model="ruleForm.paccode" autocomplete="off" placeholder="请输入封装文件编号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-input v-model="ruleForm.type" autocomplete="off" placeholder="类型" />
            </el-form-item>
          </el-col>

          <!-- prop="description" -->
          <el-col :span="24">
            <el-form-item label="封装文件描述">
              <el-input v-model="ruleForm.description" autocomplete="off" placeholder="请输入描述"
                :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="管脚数" prop="gjs">
              <el-input v-model="ruleForm.gjs" autocomplete="off" placeholder="请输入数量" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="长" prop="chang">
              <el-input v-model="ruleForm.chang" autocomplete="off" placeholder="长" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="宽" prop="kuan">
              <el-input v-model="ruleForm.kuan" autocomplete="off" placeholder="宽" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="高" prop="gao">
              <el-input v-model="ruleForm.gao" autocomplete="off" placeholder="高" />
            </el-form-item>
          </el-col>



          <el-col :span="24">
            <el-form-item label="文档权限" prop="level">
              <el-select style="width: 20%" v-model="ruleForm.level" placeholder="请选择">
                <el-option v-for="option in filesStatus" :key="option.id" :label="option.name" :value="option.id" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="24">
            <el-form-item label="评估板描述" prop="name">
              <el-row class="w-full">
                <el-col :span="24">
                  <el-input v-model="ruleForm.name" autocomplete="off" placeholder="请输入评估板描述" />
                </el-col>
                <el-col :span="24" class="mt-4">
                  <el-button>添加新描述</el-button>
                </el-col>
              </el-row>

            </el-form-item>
          </el-col> -->

        </el-row>
      </el-form>
      <el-card class="box-card" v-if="ruleForm.xzrjlist.length > 0">
        <template #header>
          <div class="card-header">
            <span>封装文件版本</span>
          </div>
        </template>
        <el-table :data="ruleForm.xzrjlist" style="width: 100%">
          <el-table-column prop="name" label="文件版本名" width="180" />
          <el-table-column prop="info" label="版本信息" />
          <el-table-column prop="gs" label="文件大小" />
          <el-table-column prop="lx" label="更新时间" />
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button @click="openOtherDialog(row)" link type="primary" size="small">编辑</el-button>
              <el-popconfirm title="确认要删除吗?" @confirm="delDataOther(row.linkid)">
                <template #reference>
                  <el-button type="danger" link>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
      </el-card>
      <el-button @click="openVisible" class="button mt-[20px]">新增文件版本</el-button>



      <el-dialog @close="closeOtherFn" v-model="dialogFormVisible" title="新增/编辑" width="30%">
        <el-form ref="ruleFormRefOther" :model="form" :rules="VisibleRules">
          <el-form-item label="版本名称" label-width="140px" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="版本详细信息" label-width="140px" prop="info">
            <el-input v-model="form.info" autocomplete="off" placeholder="请输入版本详细信息"
              :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
          </el-form-item>
          <el-form-item label="版本更新时间" label-width="140px" prop="lx">
            <el-date-picker v-model="form.lx" placeholder="请选择时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </el-form-item>

          <el-form-item label="版本文件" v-if='dialogFormVisible' label-width="140px" prop="linkList">
            <uploadFiles @success="successSize" type="other" v-model="form.linkList" @onPreviewFn="onPreviewFNother">
            </uploadFiles>
          </el-form-item>
          <el-form-item label="文档权限" prop="level" label-width="140px">
            <el-select v-model="form.level" placeholder="请选择">
              <el-option v-for="option in filesStatus" :key="option.id" :label="option.name" :value="option.id" />
            </el-select>
          </el-form-item>


        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitFormOther(ruleFormRefOther)">
              保存信息
            </el-button>
            <el-button @click="dialogFormVisible = false">取消</el-button>

          </span>
        </template>
      </el-dialog>




    </Dialog>

    <el-dialog v-model="dialogTableVisible" title="预览">
      <pdfPage v-if="pdfUrl" :source='pdfUrl'></pdfPage>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import pageTable from "@/components/base-ui/page-table";
import pageSearch from "@/components/base-ui/page-search";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref, computed } from 'vue'
import type { FormInstance, FormRules, UploadUserFile, UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage, ElMessageBox, genFileId } from 'element-plus'
import { clone } from "@pureadmin/utils";
import { randomNumber } from '@/utils/xwCommon'
import { tableInit } from "./config/table.config.ts";
import { searchFormConfig } from "./config/search.config.ts";
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import { sjcyzcrjselpackagepage, sjcyzcrjselpackageinfobyid, sjcyzcrjupdatepackage, sjcyzcrjdelpackagebyid, sjcyzcrjinsertpackage } from '@/api/packaging'
import pdfPage from "@/components/base-ui/pdf";
import uploadFiles from '@/components/base-ui/uploadFiles'
import { message } from "@/utils/message";
import { geturlneeddl } from '@/api/upload'


const {
  exportExcel,
  tableData,
  getData,
  params,
  loading,
  sizeChange,
  currentChange,
  delData,
  searchSubmit,
  DialogRef,
  openDialog,
  filesStatus,
  filterStatusName
} = usepageTable({
  tableInit,
  getRes: sjcyzcrjselpackagepage,
  delRes: sjcyzcrjdelpackagebyid,

})

getData()

const DialoLoading = ref(false)

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  chang: '',
  description: '',
  gao: '',
  gjs: '',
  kuan: '',
  level: '',
  linkList: [],
  paccode: '',
  link: '',
  pdfid: '',
  id: '',
  type: '',
  pdfname: '',
  istr: '',  //是否有跳转页面或者pdf文件（0无 1 页面 2 pdf）
  xzrjlist: []
})

const rules = reactive<FormRules<typeof ruleForm>>({
  chang: [
    { required: true, message: '请填写长', trigger: 'blur' },
  ],
  description: [
    { required: true, message: '请填写描述', trigger: 'blur' },
  ],
  gao: [
    { required: true, message: '请填写高', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请填写类型', trigger: 'blur' },
  ],

  gjs: [{ required: true, message: '请填写管脚数', trigger: 'blur' }],
  kuan: [{ required: true, message: '请填写宽', trigger: 'blur' }],
  level: [{ required: true, message: '请选择文件权限', trigger: 'blur' }],
  linkList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
  paccode: [{ required: true, message: '请填写封装编号', trigger: 'blur' }],
})
const typeText = ref('')
const openDialogFn = (text, row) => {
  typeText.value = text
  if (row) {
    sjcyzcrjselpackageinfobyid(row.id).then(res => {
      console.log(res)
      const temporary = res.result
      Object.keys(ruleForm).forEach((key) => ruleForm[key] = temporary[key])
      ruleForm.linkList = [{
        name: temporary.pdfname,
        url: temporary.pdfid,
      }]
      openDialog()
      DialoLoading.value = true
    })





    console.log(ruleForm, 'ruleForm')
  } else {
    openDialog()
    DialoLoading.value = true
  }

}


const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      ruleForm.pdfid = ruleForm.linkList[0]?.response?.data?.result[0]?.uuid ?? ruleForm.pdfid


      ruleForm.pdfname = ruleForm.linkList[0].name ?? ruleForm.pdfname

      let fn = typeText.value == '新增' ? sjcyzcrjinsertpackage : sjcyzcrjupdatepackage
      fn(ruleForm).then(() => {
        DialogRef.value.close()
        message(`${typeText.value}成功`, {
          type: 'success'
        });
        getData()
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  ruleForm.chang = ''
  ruleForm.description = ''
  ruleForm.gao = ''
  ruleForm.gjs = ''
  ruleForm.kuan = ''
  ruleForm.level = ''
  ruleForm.paccode = ''
  ruleForm.link = ''
  ruleForm.istr = ''
  ruleForm.linkList = []
  ruleForm.pdfid = ''
  ruleForm.pdfname = ''
  ruleForm.id = ''
  ruleForm.type = ''
  ruleForm.xzrjlist = []

}






const dialogTableVisible = ref(false)
const pdfUrl = ref('')
const onPreviewFN = (e) => {
  pdfUrl.value = geturlneeddl(e)
  dialogTableVisible.value = true
}


const dialogFormVisible = ref(false)
const form = reactive({
  name: '',
  lx: '',    // 自定义版本时间
  linkList: [],
  linkid: '',
  linkname: '',
  level: '',
  info: '',  //文件信息
  gs: '',  //大小
})

const openVisible = (row = {}) => {
  dialogFormVisible.value = true
}



const VisibleRules = reactive<FormRules<typeof ruleForm>>({
  name: [
    { required: true, message: '请填写版本名称', trigger: 'blur' },
  ],
  info: [
    { required: true, message: '请填写版本详细信息', trigger: 'blur' },
  ],
  lx: [
    { required: true, message: '请选版本时间', trigger: 'blur' },
  ],
  level: [
    { required: true, message: '请选择权限', trigger: 'blur' },
  ],
  linkList: [
    { required: true, message: '请上传文件', trigger: 'blur' },
  ],

})

const onPreviewFNother = (e) => {
  window.open(geturlneeddl(e))
}

const ruleFormRefOther = ref<FormInstance>()

// ruleForm.linkList = [{
//   name: temporary.pdfname,
//   url: temporary.pdfid,
// }]
const submitFormOther = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log(form, 'form')
      const temporary = clone(form, true);
      console.log('form.linkList', form.linkList)
      if (form.linkList[0].response) {
        console.log('修改了上传文件')
        temporary.linkid = form.linkList[0].response.data.result[0].uuid
        temporary.linkname = form.linkList[0].response.data.result[0].name
      } else {
        temporary.linkid = ruleForm.linkList[0].url
        temporary.linkname = ruleForm.linkList[0].name
      }

      if (otherFlag.value) {
        ruleForm.xzrjlist.forEach(v => {
          if (v.id === otherFlag.value) {
            Object.keys(form).forEach((key) => v[key] = temporary[key])
          }
        })
      } else {
        ruleForm.xzrjlist.unshift(temporary)
      }

      dialogFormVisible.value = false
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const successSize = (size) => {
  form.gs = size
}

const delDataOther = (id) => {
  let otherList = ruleForm.xzrjlist.filter(v => v.linkid != id)
  ruleForm.xzrjlist = otherList
}

const openOtherDialog = (row) => {
  // otherDialoLoading.value = true
  otherFlag.value = row.id
  Object.keys(form).forEach((key) => form[key] = row[key])
  form.linkList = [{
    name: row.linkname,
    url: row.linkid,
  }]
  dialogFormVisible.value = true
}


const otherFlag = ref('')  //true 为编辑
const closeOtherFn = () => {
  form.name = ''
  form.lx = ''
  form.linkList = []
  form.linkid = ''
  form.linkname = ''
  form.level = ''
  form.info = ''
  form.gs = ''
  otherFlag.value = ''
  console.log(form, 'form回调')
}

</script>

<style scoped></style>
